package com.example.testnetty.netty;

import android.util.Log;

import com.example.testnetty.activity.AESUtils;
import com.example.testnetty.eventbus.MainMsg;

import org.greenrobot.eventbus.EventBus;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;

/**
 * Author:ZJC
 * Date:2020/4/11  11:31
 * Description:NettyManager
 */
public class NettyManager implements NettyListener {

    private String TAG = "tian";
    public static volatile NettyManager instance = null;
    private NettyClient nettyClient = null;

    public NettyManager() {
        nettyClient = new NettyClient();
    }

    public static NettyManager getInstance() {
        if (instance == null) {
            synchronized (NettyManager.class) {
                if (instance == null) {
                    instance = new NettyManager();
                }
            }
        }
        return instance;
    }

    public void connectNetty() {
        new Thread(() -> {
            EventBus.getDefault().post(new MainMsg("ip:" + Constans.HOST + ",port:" + Constans.TCP_PORT));
            EventBus.getDefault().post(new MainMsg("客户端启动自动连接..."));
            Log.e(TAG, "客户端启动自动连接...");
            if (!nettyClient.getConnectStatus()) {
                nettyClient.setListener(NettyManager.this);
                nettyClient.connect();
            } else {
                nettyClient.disconnect();
            }
        }).start();
    }

    public void sendData(String data) {
        nettyClient.sendMsgToServer(data, new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    EventBus.getDefault().post(new MainMsg("发送成功"));
                    Log.e(TAG, "发送成功");
                } else {
                    EventBus.getDefault().post(new MainMsg("发送失败"));
                    Log.e(TAG, "发送失败");
                }
            }
        });
    }

    public void sendDataByte(String data) {
        nettyClient.sendMsgByteToServer(data, new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    EventBus.getDefault().post(new MainMsg("发送成功"));
                    Log.e(TAG, "发送成功");
                } else {
                    EventBus.getDefault().post(new MainMsg("发送失败"));
                    Log.e(TAG, "发送失败");
                }
            }
        });
    }

    @Override
    public void onMessageResponse(Object msg) {
        ByteBuf result = (ByteBuf) msg;
        byte[] result1 = new byte[result.readableBytes()];
        result.readBytes(result1);
        result.release();
        String results = new String(result1);
        String ss = "";
        if (results.startsWith("brand")) {
            byte[] brand = new byte[result1.length - 5];
            System.arraycopy(result1,5,brand,0,brand.length);
            byte[] bytedecrypt = AESUtils.bytedecrypt(brand);
            ss = new String(bytedecrypt);
        } else {
            byte[] bytedecrypt = AESUtils.bytedecrypt(result1);
            ss = new String(bytedecrypt);
        }


        EventBus.getDefault().post(new MainMsg("来自服务端的消息:" + ss));
        Log.e(TAG, "来自服务端的消息:" + ss);
    }

    @Override
    public void onServiceStatusConnectChanged(int statusCode) {
        if (statusCode == NettyListener.STATUS_CONNECT_SUCCESS) {
            Log.e(TAG, "STATUS_CONNECT_SUCCESS:");
            if (nettyClient.getConnectStatus()) {
                EventBus.getDefault().post(new MainMsg("连接成功"));
                Log.e(TAG, "连接成功");
            }
        } else {
            Log.e(TAG, "onServiceStatusConnectChanged:" + statusCode);
            if (!nettyClient.getConnectStatus()) {
                EventBus.getDefault().post(new MainMsg("网路不好，正在重连"));
                Log.e(TAG, "网路不好，正在重连");
            }
        }
    }

    public void close() {
        if (nettyClient != null) {
            nettyClient.disconnect();
        }
    }
}